package com.admin.controller.admin;


import com.github.pagehelper.PageInfo;
import com.system.annotation.Log;
import com.system.constant.HTTPStatus;
import com.system.emus.BusinessType;
import com.system.entity.*;
import com.system.response.Result;
import com.system.response.role.RoleDtoResponse;
import com.system.service.MenuService;
import com.system.service.PermissionService;
import com.system.service.RoleService;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.List;

/**
 * <p>
 * 角色表 前端控制器
 * </p>
 *
 * @author zfc
 * @since 2023-04-20
 */

@RequiresAuthentication
@Validated
@RestController
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private RoleService roleService;

    @Autowired
    private MenuService menuService;

    @Autowired
    private PermissionService permissionService;

    @Cacheable(
            value = "role",
            key = "#roleResponse.pageSize +'::'+ #roleResponse.pageNum +'::'+ #roleResponse.name +'::'+ #roleResponse.delete"
    )
    @PostMapping("/limit")
    @ApiOperation("分页（条件）查询角色")
    public Result limit(@RequestBody RoleDtoResponse roleResponse) {
        PageInfo<Role> info = roleService.roleLimit(roleResponse);
        return new Result().setCode(HTTPStatus.SUCCESS).setData(info);
    }

    @Log(title = "角色管理",businessType = BusinessType.INSERT)
    @CacheEvict(
            value = "role",
            allEntries = true
    )
    @RequiresPermissions("admin:role:add")
    @PostMapping("/addRole")
    @ApiOperation("新增角色")
    public Result addRole(@Validated @RequestBody Role role) {
        boolean unique = roleService.checkRoleUnique(role);

        if (unique) {
            return new Result().setCode(HTTPStatus.BAD_REQUEST).setMessage("角色【" + role.getRoleName() + "】已存在。");
        } else {
            boolean addRole = roleService.addRole(role);
            if (addRole) {
                return new Result().setCode(HTTPStatus.SUCCESS).setMessage("角色【" + role.getRoleName() + "】新增成功。");
            } else {
                return new Result().setCode(HTTPStatus.BAD_REQUEST).setMessage("角色【" + role.getRoleName() + "】新增失败，请联系管理员！");
            }
        }
    }

    @Log(title = "角色管理",businessType = BusinessType.FREEZE)
    @CacheEvict(
            value = "role",
            allEntries = true
    )
    @RequiresPermissions("admin:role:delete")
    @DeleteMapping("/deleteRole")
    @ApiOperation("删除角色（修改角色状态")
    public Result deleteRole(@RequestBody Role role) {
        //后续这里如果有权限什么的关联了角色，角色则不可以被删除

        //1、检查角色是否绑定了教师（用户）
        TeacherRole newTR = new TeacherRole();
        newTR.setRoleId(role.getId());
        boolean teacherBoundRoles = roleService.checkTeacherBoundRoles(newTR);
        if (teacherBoundRoles){
            return new Result().setCode(HTTPStatus.BAD_REQUEST).setMessage("该角色已被使用，不能停用（已绑定用户）");
        }
        //2、检查角色是否绑定了菜单
        RoleMenu newRM = new RoleMenu();
        newRM.setRoleId(role.getId());
        boolean roleBoundMenus = menuService.checkRoleBoundMenus(newRM);
        if (roleBoundMenus){
            return new Result().setCode(HTTPStatus.BAD_REQUEST).setMessage("该角色已被使用，不能停用（已绑定菜单）");
        }
        //3、检查角色是否绑定了权限
        RolePermission newRp = new RolePermission();
        newRp.setRoleId(role.getId());
        boolean roleBoundPermission = permissionService.checkRoleBoundPermission(newRp);
        if (roleBoundPermission){
            return new Result().setCode(HTTPStatus.BAD_REQUEST).setMessage("该角色已被使用，不能停用（已绑定权限   ）");
        }

        Role newRole = new Role();
        newRole.setId(role.getId());
        newRole.setIsDelete(role.getIsDelete());

        boolean updateRole = roleService.updateRole(newRole);

        String statusStr = role.getIsDelete() == 0 ? "恢复":"停用";

        if (updateRole) {
            return new Result().setCode(HTTPStatus.SUCCESS).setMessage(statusStr+"成功。");
        } else {
            return new Result().setCode(HTTPStatus.BAD_REQUEST).setMessage(statusStr+"失败，请联系管理员！");
        }
    }

    @Log(title = "角色管理",businessType = BusinessType.DELETE)
    @CacheEvict(
            value = "role",
            allEntries = true
    )
    @RequiresPermissions("admin:role:completelyDelete")
    @DeleteMapping("/completelyDeleteRole")
    @ApiOperation("彻底删除角色")
    public Result deleteRole(@NotNull(message = "角色编号不能为空") Integer id) {

        boolean updateRole = roleService.completelyDeleteRoleById(id);

        if (updateRole) {
            return new Result().setCode(HTTPStatus.SUCCESS).setMessage("彻底删除成功。");
        } else {
            return new Result().setCode(HTTPStatus.BAD_REQUEST).setMessage("彻底删除失败，请联系管理员！");
        }
    }

    @Log(title = "角色管理",businessType = BusinessType.UPDATE)
    @CacheEvict(
            value = "role",
            allEntries = true
    )
    @RequiresPermissions("admin:role:update")
    @PutMapping("/updateRole")
    @ApiOperation("修改角色")
    public Result updateRole(@Validated @RequestBody Role role){

        //检查修改的名称是否存在，如果修改名称还是原名称则可以修改
        boolean isOneself = roleService.checkRoleNameIsOneself(role);

        boolean unique = roleService.checkRoleUnique(role);

        if (unique && isOneself) {
            return new Result().setCode(HTTPStatus.BAD_REQUEST).setMessage("角色【" + role.getRoleName() + "】已存在。");
        }

        boolean updateRole = roleService.updateRole(role);

        if (updateRole) {
            return new Result().setCode(HTTPStatus.SUCCESS).setMessage("角色【"+role.getRoleName()+"】修改成功。");
        } else {
            return new Result().setCode(HTTPStatus.BAD_REQUEST).setMessage("角色【"+role.getRoleName()+"】修改失败，请联系管理员！");
        }
    }

    @Cacheable(
            value = "role",
            key = "#root.methodName +'::'+ #id"
    )
    @GetMapping("/selectRoleById")
    @ApiOperation("查询角色通过角色编号")
    public Result selectRoleById(@NotNull(message = "角色编号不能为空") Integer id){
        Role role = roleService.selectRoleById(id);
        return new Result<>().setCode(HTTPStatus.SUCCESS).setData(role);
    }

    @Cacheable(
            value = "role",
            key = "#root.methodName"
    )
    @GetMapping("/selectAllRole")
    @ApiOperation("查询所有角色")
    public Result selectAllRole(){
        List<Role> roles = roleService.selectAllRole();
        return new Result<>().setCode(HTTPStatus.SUCCESS).setData(roles);
    }

    /**
     * ------------------------------角色 绑定 菜单-----------------------------------------
     */

    @GetMapping("/queryRoleBoundMenus")
    @ApiOperation("查询角色绑定的菜单")
    public Result queryRoleUnBoundMenus(Integer id){
        List<Menu> menuList = menuService.queryRolesBoundMenus(id);
        return new Result<>().setCode(HTTPStatus.SUCCESS).setData(menuList);
    }

    /**
     * ------------------------------角色 绑定 权限-----------------------------------------
     */

    @GetMapping("/queryPermissionBoundRoles")
    @ApiOperation("查询角色绑定的权限")
    public Result queryPermissionUnBoundRoles(Integer id){
        List<Permission> permissionList = permissionService.queryRolesBoundPermission(id);
        return new Result<>().setCode(HTTPStatus.SUCCESS).setData(permissionList);
    }

}
